package hotel.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import hotel.dao.GuestConditionDao;
import hotel.pojo.GuestDto;
import hotel.pojo.ManagerDto;

@Repository
public class GuestConditionDaoImpl implements GuestConditionDao {
	
	@Resource(name="mysqlJdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	public boolean checkIn(String room,String name,String sex,String age,String tel,String id,String time,String mony) {
		String state = "1";
		String sql = "INSERT INTO guest VALUES(?,?,?,?,?,?,?,?,?)";
		String sql1 = "UPDATE room SET Rstate = '1' WHERE Rnum = ?";
		int influence = 0;
		try {
			influence = jdbcTemplate.update(sql, new Object[] {name,sex,age,tel,id,room,time,mony,state});
		}catch( DataAccessException e) {
			System.out.println(e.getMessage());
			return false;
		}
		try {
			influence = jdbcTemplate.update(sql1, new Object[] {room});
		}catch(DataAccessException e) {
			System.out.println(e.getMessage());
			return false;
		}
		if(influence == 0) {
			return false;
		}
		return true;
	}

	public List<GuestDto> guestMessage(String message, String status) {
		 String selectByName = "SELECT * FROM guest WHERE name = ?";
		 String selectByTel = "SELECT * FROM guest WHERE tel = ?";
		 String selectById = "SELECT * FROM guest WHERE id = ?";
		 String selectByRoom = "SELECT * FROM guest WHERE room = ?";
		 String sql;
		 switch(Integer.parseInt(status)) {
		 case 1 :
			 sql = selectByName;
			 break;
		 case 2 :
			 sql = selectByTel;
			 break;
		case 3 :
			sql = selectById;
			break;
		case 4 :
			sql = selectByRoom;
			break;
		default:
			return null;
		 }
		 ResultSetExtractor<List<GuestDto>> lists = new ResultSetExtractor<List<GuestDto>>() {
			 
				public List<GuestDto> extractData(ResultSet rs) throws SQLException, DataAccessException{
					List<GuestDto> lists = new ArrayList<GuestDto>();
					while(rs.next()) {
						String name = rs.getString("name");
						String sex = rs.getString("sex");
						String age = rs.getString("age");
						String tel = rs.getString("tel");
						String id = rs.getString("id");
						String room = rs.getString("room");
						String time = rs.getString("time");
						String mony = rs.getString("mony");
						String state = rs.getString("state");
						GuestDto guestDto = new GuestDto(name,sex,age,tel,id,room,time,mony,state);
						lists.add(guestDto);
					}
					return lists;
				}
			};	
			return jdbcTemplate.query(sql,new Object[] {message},lists);
	}
	
}
